#!/bin/bash
cd ~/app-root/repo/扩展/
List=$(ls *[0-9].xpi)
if [ "$List" ]; then
    for i in $List; do
        unzip -o $i install.rdf
        xpiID=$(grep '<em:id\>' install.rdf|sed '2,$d'|awk -F '>' '{print $2}'|awk -F '<' '{print $1}')
        xpiVersion=$(grep -o "[0-9]\{2\}\.[0-9]\{2\}\.[0-9]\{2\}\.[0-9]\{2\}" install.rdf)
        curl -s "https://addons.mozilla.org/api/v3/addons/$xpiID/versions/$xpiVersion/" -g -XPUT --form "upload=@$i" -H "Authorization: JWT $(python ~/app-root/data/github-sh/xpi/pyjwt/pyjwt.py)"
        rm -f $i
        for ((n=1;n<=10;n++)); do
            result=$(curl "https://addons.mozilla.org/api/v3/addons/$xpiID/versions/$xpiVersion/" -g -H "Authorization: JWT $(python ~/app-root/data/github-sh/xpi/pyjwt/pyjwt.py)")
            if echo $result | grep -q 'signed\":true'; then
                rm -f `echo "$i" |sed "s#-.*\.xpi.*#-#"`*
                xpiUrl=$(echo "$result" |grep -o https://addons.mozilla.org/api/v3/file/".*".xpi?src=api )
                xpiName=$(echo "$i" |sed -e "s#-.*\.xpi.*#-${xpiVersion}-signed.xpi#" -e 's#_##g' )
                curl $xpiUrl -L -g -H "Authorization: JWT $(python ~/app-root/data/github-sh/xpi/pyjwt/pyjwt.py)" -o $xpiName
                break 1
            else
                sleep 5
            fi
        done
    done
fi
rm -f install.rdf